package com.rockcent.api.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.api.Routes;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.RBeanUtils;
import com.rockcent.helper.AuthResourceHelper;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.SystemType;
import com.rockcent.mall.lib.dto.AuthResourceDto;
import com.rockcent.mall.lib.dto.AuthUserResourceDefaultDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.dto.UserMallDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.*;
import com.rockcent.service.AuthUserResourceSrv;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Created by DK on 17/3/28.
 * M端账户管理
 */
@RestController
@RequestMapping(value = Routes.API_VERSION)
public class SSOMallController  extends BaseController {

    private final Logger log = LoggerFactory.getLogger(SSOMallController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private AuthUserResourceDefaultRepository authUserResourceDefaultRepository;

    @Autowired
    private AuthResourceRepository authResourceRepository;

    @Autowired
    private MallRepository mallRepository;

    @Autowired
    private AuthUserResourceRepository authUserResourceRepository;

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private UserMallRepository userMallRepository;

    @Autowired
    private AuthTitleRepository authTitleRepository;

    @Autowired
    private AuthTitleResourceRepository authTitleResourceRepository;

    @Autowired
    private AuthUserResourceSrv authUserResourceSrv;

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * @api {post} /v1/sso/mall_resource/default_save  M端默认权限 保存(R端调用)
     * @apiGroup SSO-USER-MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     *
     *
     * @apiParam {Long} resourceIdList  菜单ID集合 例如:[1,2,3]
     *
     * @apiSuccessExample {json} Success-Resp：
     * {
     *   "code": "1",
     *   "desc": "成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.SSO_MALL_DEFAULT_RESOURCE_SAVE, method = RequestMethod.POST)
    public JsonResult mallDefaultResourceSave(HttpServletRequest request, @RequestBody AuthUserResourceDefaultDto dto) {
        RestDoing doing = jsonResult -> {
            if (dto.getResourceIdList().size() > 0) {
                authUserResourceSrv.saveAuthUserResourceDefault(dto.getResourceIdList(), SystemType.MALL);
            }
        };
        return doing.go(request, log);
    }
    /**
     * @api {post} /v1/sso/mall_resource/default_update  M端默认权限 更改(R端调用)
     * @apiGroup SSO-USER-MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     *
     *
     * @apiParam {Long} resourceIdList  菜单ID集合 例如:[1,2,3]
     *
     * @apiSuccessExample {json} Success-Resp：
     * {
     *   "code": "1",
     *   "desc": "成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.SSO_MALL_DEFAULT_RESOURCE_UPDATE, method = RequestMethod.POST)
    public JsonResult mallDefaultResourceUpdate(HttpServletRequest request, @RequestBody AuthUserResourceDefaultDto dto) {
        RestDoing doing = jsonResult -> {
            List<AuthUserResourceDefault> authUserResourceDefaultList = authUserResourceDefaultRepository.findBySystemType(SystemType.MALL);
            authUserResourceDefaultRepository.delete(authUserResourceDefaultList);
            if (dto.getResourceIdList().size() > 0) {
                authUserResourceSrv.saveAuthUserResourceDefault(dto.getResourceIdList(), SystemType.MALL);
            }
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /v1/sso/mall_resource/info  M端权限 详情(R端调用)
     * @apiGroup SSO-USER-MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     *
     *
     * @apiParam {Long} id <code>必传参数</code> 平台ID
     *
     * @apiSuccessExample {json} Success-Resp：
     * {
     *   "code": "1",
     *   "desc": "成功"
     * }
     */
    @RequestMapping(value = Routes.SSO_MALL_RESOURCE_INFO, method = RequestMethod.GET)
    public JsonResult mallResourceInfo(HttpServletRequest request, UserMallDto dto) {
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind(Mall.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            Mall mall = mallRepository.findOne(dto.getId());
            if (mall == null) {
                jsonResult.remind(Mall.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            UserMall userMall = userMallRepository.findByMallIdAndUserId(mall.getId(), mall.getUserInfoId());
            if (userMall == null) {
                jsonResult.remind("平台账户权限不存在",log);
                return;
            }
            List<AuthUserResource> authUserResourceList = authUserResourceRepository.findByMallIdAndUserId(mall.getId(), mall.getUserInfoId());
            List<Long> resourceIdList = authUserResourceList.stream().map(AuthUserResource::getResourceId).collect(Collectors.toList());
            RBeanUtils.copyProperties(userMall, dto);
            dto.setResourceIdList(resourceIdList);
            dto.setMallName(mall.getName());
            jsonResult.data = dto;
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /v1/sso/mall_resource/update  M端权限 更改(R端调用)
     * @apiGroup SSO-USER-MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     *
     *
     * @apiParam {Long} id <code>必传参数</code> 平台ID
     * @apiParam {String} username <code>必传参数</code> 账号
     * @apiParam {String} name <code>必传参数</code> 使用者
     * @apiParam {String=ADMIN("R端"),MALL("M端"),MERCHANT("B端")} systemType <code>必传参数</code> 系统类型
     * @apiParam {Long} resourceIdList  菜单ID集合 例如:[1,2,3]
     *
     * @apiSuccessExample {json} Success-Resp：
     * {
     *   "code": "1",
     *   "desc": "成功"
     * }
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @RequestMapping(value = Routes.SSO_MALL_RESOURCE_UPDATE, method = RequestMethod.PUT)
    public JsonResult mallResourceUpdate (HttpServletRequest request, @RequestBody AuthUserResourceDefaultDto dto) {
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind("平台ID 不能为空",log);
                return;
            }

            Mall mall = mallRepository.findOne(dto.getId());
            if (mall == null) {
                jsonResult.remind("平台不存在",log);
                return;
            }

            //菜单权限
            List<AuthUserResource> authUserResourceList = authUserResourceRepository.findByMallId(mall.getId());

            //过滤得出平台的菜单权限
            List<AuthUserResource> mallAuthUserResourceList = authUserResourceList.stream().filter(authUserResource -> Objects.equals(authUserResource.getUserId(), mall.getUserInfoId())).collect(Collectors.toList());

            //过滤得出平台子账号的菜单权限
            List<AuthUserResource> mallSonAuthUserResourceList = authUserResourceList.stream().filter(authUserResource -> !Objects.equals(authUserResource.getUserId(), mall.getUserInfoId())).collect(Collectors.toList());

            //平台的原有的菜单权限
            List<Long> resourceIdList = mallAuthUserResourceList.stream().map(AuthUserResource::getResourceId).collect(Collectors.toList());

            //平台职称的菜单权限
            List<AuthTitleResource> authTitleResourceList = authTitleResourceRepository.findByOwnerIdAndSystemTypeAndIsDelete(dto.getId(), SystemType.valueOf(dto.getSystemType()), Whether.NO);

            //删除平台原有菜单权限
            authUserResourceRepository.delete(authUserResourceList);

            if (dto.getResourceIdList().size() > 0) {
                //删除平台的菜单权限
                List<Long> delResourceIdList = resourceIdList.stream().filter(resourceId -> !dto.getResourceIdList().contains(resourceId)).collect(Collectors.toList());
                //重新添加平台原有菜单权限
                authUserResourceSrv.updateAuthUserResource(dto.getResourceIdList(), mall.getUserInfoId(), mall.getId(), null);

                if (delResourceIdList.size() > 0) {
                    //更改平台子账号的菜单权限
                    for (AuthUserResource userResource : mallSonAuthUserResourceList) {
                        delResourceIdList.stream().filter(resourceId -> Objects.equals(userResource.getResourceId(), resourceId)).forEach(resourceId -> {
                            authUserResourceRepository.delete(userResource);
                        });
                    }
                    //更改平台角色的菜单权限
                    for (AuthTitleResource titleResource : authTitleResourceList) {
                        delResourceIdList.stream().filter(resourceId -> Objects.equals(titleResource.getResourceId(), resourceId)).forEach(resourceId -> {
                            authTitleResourceRepository.delete(titleResource);
                        });
                    }
                }
            }


        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /v1/sso/mall_resource/tree  M端权限 树形(M端调用)
     * @apiGroup SSO-USER-MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id <code>必传参数</code> 平台ID
     *
     * @apiSuccess {long} id 菜单ID
     * @apiSuccess {long} parentId 父ID
     * @apiSuccess {long} sort 顺序
     * @apiSuccess {String} iconName 图标名称
     * @apiSuccess {String} name 菜单名称
     * @apiSuccess {String} frontendUrl 前端url
     * @apiSuccess {String} backendUrl 后端url
     * @apiSuccess {String=ADMIN("R端"),MALL("M端"),MERCHANT("B端")} systemType 系统类型
     * @apiSuccessExample {json} Success-Response:
     *  {
     *      "code": 1,
     *      "desc": "成功",
     *      "data" :[
     *                   {
     *                   "id": 5,
     *                   "dateCreated": "2017-03-14 18:58:37",
     *                   "lastUpdated": "2017-03-14 18:58:37",
     *                   "iconName": "菜单1级",
     *                   "name": "菜单1级",
     *                   "sort": 1,
     *                   "systemType": "MALL",
     *                   "backendUrl": "http://baidu.com/",
     *                   "authResourceList": [
     *                          {
     *                          "id": 6,
     *                          "dateCreated": "2017-03-14 18:59:25",
     *                          "lastUpdated": "2017-03-14 18:59:25",
     *                          "parentId": 5,
     *                          "iconName": "菜单2级",
     *                          "name": "菜单2级",
     *                          "sort": 1,
     *                          "systemType": "MALL",
     *                          "backendUrl": "http://baidu.com/",
     *                          "authResourceList": []
     *                          },
     *                          {
     *                          "id": 7,
     *                          "dateCreated": "2017-03-15 11:56:24",
     *                          "lastUpdated": "2017-04-01 02:00:53",
     *                          "parentId": 5,
     *                          "iconName": "2级标题",
     *                          "name": "2级标题",
     *                           "*sort": 2,
     *                           "systemType": "MALL",
     *                           "backendUrl": "11111",
     *                           "authResourceList": [
     *                              {
     *                              "id": 8,
     *                              "dateCreated": "2017-03-15 11:58:18",
     *                              "lastUpdated": "2017-04-01 02:01:01",
     *                              "parentId": 7,
     *                              "iconName": "3级标题",
     *                              "name": "3级标题",
     *                              "sort": 3,
     *                              "systemType": "MALL",
     *                              "backendUrl": "11111",
     *                              "authResourceList": [
     *                                  {
     *                                  "id": 9,
     *                                  "dateCreated": "2017-03-15 13:48:11",
     *                                  "lastUpdated": "2017-04-01 02:01:12",
     *                                  "parentId": 8,
     *                                  "iconName": "4级标题",
     *                                  "name": "4级标题",
     *                                  "sort": 4,
     *                                  "systemType": "MALL",
     *                                  "backendUrl": "11111"
     *                                  },
     *                                  {
     *                                  "id": 10,
     *                                  "dateCreated": "2017-03-15 13:57:43",
     *                                  "lastUpdated": "2017-04-01 02:01:15",
     *                                  "parentId": 8,
     *                                  "iconName": "4级标题",
     *                                  "name": "4级标题",
     *                                  "sort": 5,
     *                                  "systemType": "MALL",
     *                                  "backendUrl": "/admin/user"
     *                                  }
     *                            ]
     *                       }
     *                 ]
     *           }
     *       ]
     *      }
     *    ]
     *   }
     */
    @RequestMapping(value = Routes.SSO_MALL_RESOURCE_TREE, method = RequestMethod.GET)
    public JsonResult mallResourceTree(HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            //M端的所有菜单权限
            List<AuthResourceDto> authResourceList = authResourceRepository.findAuthResourceDtoList(SystemType.MALL.toString());
            //平台拥有的菜单权限
//            List<AuthUserResource> authUserResourceList = authUserResourceRepository.findByMallIdAndUserId(userInfoDto.mall.getId(), userInfoDto.getId());
//            jsonResult.data = authUserResourceSrv.authUserResourceTree(authResourceList, authUserResourceList);
            if(authResourceList!=null && authResourceList.size()>0) {
                for(AuthResourceDto authResourceDto:authResourceList) {
                    if (StringUtils.isNotBlank(authResourceDto.getBackendUrl())) {
                        authResourceDto.setBackendUrlList(objectMapper.readValue(authResourceDto.getBackendUrl(), new TypeReference<List<String>>() {}));
                    }else {
                        authResourceDto.setBackendUrlList(new ArrayList<>());
                    }
                }
                jsonResult.data= AuthResourceHelper.SINGLETON.createTree(null,authResourceList);
            }
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /v1/sso/mall_child_account/page M端子账号 分页(M端调用)
     * @apiGroup SSO-USER-MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {long} titleId 职称Id
     *
     * @apiSuccess {long} id 主ID
     * @apiSuccess {long} userId 用户ID
     * @apiSuccess {String} username 账户名
     * @apiSuccess {String} name 使用者
     * @apiSuccess {String} titleName 职称名称
     * @apiSuccess {long} titleId 职称Id
     * @apiSuccess {String} isSuperAdmin 是否超级管理员
     * @apiSuccess {String=YES("启用"), NO("停止")} available 是否启用
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *      "data": [
     *          {
     *              "id": 1,
     *              "dateCreated": "2017-03-09 18:04:57",
     *              "lastUpdated": "2017-03-09 18:06:07",
     *              "version": 0,
     *              "userId": 545,
     *              "username": "13450286811",
     *              "titleName": "网管",
     *              "name": "超级管理员",
     *              "isSuperAdmin": "YES",
     *              "available": "YES"
     *          }
     *      ],
     *      "totalCount": 1,
     *      "totalPage": 1,
     *      "pageNo": 0,
     *      "pageSize": 10,
     *      "url": "/sso/user_admin/page",
     *      "prevUrl": "/sso/user_admin/page?pageNo=0&pageSize=10",
     *      "nextUrl": "/sso/user_admin/page?pageNo=0&pageSize=10"
     *   }
     * }
     */
    @RequestMapping(value = Routes.SSO_MALL_CHILD_ACCOUNT_PAGE, method = RequestMethod.GET)
    public JsonResult mallChildAccountResourcePage (HttpServletRequest request, UserMallDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            PageResult<UserMallDto> pageResult = userMallRepository.findMallChildAccountResourcePage(dto.getTitleId(), userInfoDto.mall.getId(), this.getPage(dto.getPageNo(), dto.getPageSize()));
            pageResult.setUrl(Routes.SSO_MALL_CHILD_ACCOUNT_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }


    /**
     * @api {post} /v1/sso/mall_child_account_resource/save  M端子账号权限 保存(M端调用)
     * @apiGroup SSO-USER-MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} titleId <code>必传参数</code> 角色ID
     * @apiParam {String} username <code>必传参数</code> 账号
     * @apiParam {String} name <code>必传参数</code> 使用者
     *
     * @apiSuccessExample {json} Success-Resp：
     * {
     *   "code": "1",
     *   "desc": "成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.SSO_MALL_CHILD_ACCOUNT_RESOURCE_SAVE, method = RequestMethod.POST)
    public JsonResult mallChildAccountResourceSave (HttpServletRequest request, @RequestBody UserMallDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {

            if (StringUtils.isBlank(dto.getUsername())) {
                jsonResult.remind("账户名 不能为空",log);
                return;
            }
            if (StringUtils.isBlank(dto.getName())) {
                jsonResult.remind("使用者 不能为空",log);
                return;
            }
            if (dto.getTitleId() == null) {
                jsonResult.errorParam("职称id不能为空",log);
                return;
            }

            AuthTitle authTitle = authTitleRepository.findOne(dto.getTitleId());
            if (authTitle == null) {
                jsonResult.remind("职称不存在",log);
                return;
            }

            UserInfo userInfo = userInfoRepository.findByUsername(dto.getUsername());
            if (userInfo == null) {
                jsonResult.remind("账户名不存在,请先注册",log);
                return;
            }

            UserMall userMall = userMallRepository.findByMallIdAndUserId(userInfoDto.mall.getId(), userInfo.getId());
            if (userMall != null) {
                jsonResult.remind("此账户已存在平台",log);
                return;
            }else {
                userMall = new UserMall();
            }
            userMall.setMallId(userInfoDto.mall.getId());
            userMall.setIsSuperAdmin(Whether.NO);
            userMall.setName(dto.getName());
            userMall.setUserId(userInfo.getId());
            userMall.setUsername(userInfo.getUsername());
            userMall.setTitleId(authTitle.getId());
            userMall.setTitleName(authTitle.getName());
            userMall = userMallRepository.save(userMall);

            //添加菜单权限
            List<AuthTitleResource> authTitleResourceList = authTitleResourceRepository.findByTitleId(authTitle.getId());
            authUserResourceSrv.saveAuthUserResource(authTitleResourceList, userMall.getUserId(), userInfoDto.mall.getId(), null);
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /v1/sso/mall_child_account_resource/update  M端子账号权限 更改(M端调用)
     * @apiGroup SSO-USER-MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id <code>必传参数</code> M端子账号id
     * @apiParam {Long} titleId <code>必传参数</code> 角色ID
     * @apiParam {String} username <code>必传参数</code> 账号
     * @apiParam {String} name <code>必传参数</code> 使用者
     * @apiParam {Long} resourceIdList  菜单ID集合 例如:[1,2,3]
     *
     * @apiSuccessExample {json} Success-Resp：
     * {
     *   "code": "1",
     *   "desc": "成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.SSO_MALL_CHILD_ACCOUNT_RESOURCE_UPDATE, method = RequestMethod.PUT)
    public JsonResult mallChildAccountResourceUpdate (HttpServletRequest request, @RequestBody UserMallDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Long dtoId = dto.getId();
            if (dtoId == null) {
                jsonResult.remind("子账号ID 不能为空",log);
                return;
            }
            Long titleId = dto.getTitleId();
            if (titleId == null) {
                jsonResult.errorParam("职称id不能为空",log);
                return;
            }
            String dtoName = dto.getName();
            if (StringUtils.isBlank(dtoName)) {
                jsonResult.remind("使用者 不能为空",log);
                return;
            }
            String dtoUsername = dto.getUsername();
            if (StringUtils.isBlank(dtoUsername)) {
                jsonResult.remind("账号 不能为空",log);
                return;
            }
            AuthTitle authTitle = authTitleRepository.findOne(titleId);
            if (authTitle == null) {
                jsonResult.remind("职称不存在",log);
                return;
            }
            UserMall userMall = userMallRepository.findOne(dtoId);
            if (userMall == null) {
                jsonResult.remind("子账号不存在",log);
                return;
            }
            Long userId = userMall.getUserId();
            UserInfo userInfo = userInfoRepository.findOne(userId);
            if (userInfo == null) {
                jsonResult.remind("子账号没有完成注册",log);
                return;
            }
            if (userMall.getIsSuperAdmin() == Whether.YES) {
                jsonResult.remind("不能对超级管理员配置权限",log);
                return;
            }
            if (Objects.equals(userInfoDto.getId(), userInfo.getId())) {
                jsonResult.remind("不能对自己设置权限",log);
                return;
            }
            userMall.setName(dtoName);
            Long mallId = userMall.getMallId();
//            List<AuthUserResource> authUserResourceList = authUserResourceRepository.findByMallIdAndUserId(mallId, userId);
//            authUserResourceRepository.delete(authUserResourceList);
            // 当改变角色时，所有权限重新设置
//            if (!userMall.getTitleId().equals(authTitle.getId())) {
                userMall.setTitleId(authTitle.getId());
                userMall.setTitleName(authTitle.getName());
                // 重新设置
                //List<AuthTitleResource> authTitleResourceList = authTitleResourceRepository.findByTitleId(authTitle.getId());
                //authUserResourceSrv.saveMallAuthUserResource(authTitleResourceList, userMall);
                authUserResourceSrv.saveAuthTitleResourceAndAuthUserResource(authTitle.getId(),userMall.getUserId(),userMall.getMallId(),null,SystemType.MALL);
                userMallRepository.save(userMall);
//            }
//            List<Long> resourceIdList = dto.getResourceIdList();
//            authUserResourceSrv.updateAuthUserResource(resourceIdList, userMall.getUserId(), userMall.getMallId(), null);
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /v1/sso/mall_child_account_resource/info M端子账号权限 详情(M端调用)
     * @apiGroup SSO-USER-MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id <code>必传参数</code> M端子账号id
     *
     * @apiSuccessExample {json} Success-Resp：
     * {
     *   "code": "1",
     *   "desc": "成功"
     * }
     */
    @RequestMapping(value = Routes.SSO_MALL_CHILD_ACCOUNT_RESOURCE_INFO, method = RequestMethod.GET)
    public JsonResult mallChildAccountResourceInfo (HttpServletRequest request, UserMallDto dto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind("子账号ID 不能为空",log);
                return;
            }
            UserMall userMall = userMallRepository.findOne(dto.getId());
            if (userMall == null) {
                jsonResult.remind("子账号不存在",log);
                return;
            }
            UserInfo userInfo = userInfoRepository.findOne(userMall.getUserId());
            if (userInfo == null) {
                jsonResult.remind("子账号没有完成注册",log);
                return;
            }
            List<AuthUserResource> authUserResourceList = authUserResourceRepository.findAuthUserResourceByMallIdAndUserId(userMall.getMallId(), userInfo.getId());
            List<Long> resourceIdList = authUserResourceList.stream().map(AuthUserResource::getResourceId).collect(Collectors.toList());
            RBeanUtils.copyProperties(userMall, dto);
            dto.setResourceIdList(resourceIdList);
            jsonResult.data = dto;
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /v1/sso/mall_child_account_resource/delete M端子账号 删除(M端调用)
     * @apiGroup SSO-USER-MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id <code>必传参数</code> M端子账号id
     *
     * @apiSuccessExample {json} Success-Resp：
     * {
     *   "code": "1",
     *   "desc": "成功"
     * }
     */
    @RequestMapping(value = Routes.SSO_MALL_CHILD_ACCOUNT_RESOURCE_DELETE, method = RequestMethod.PUT)
    public JsonResult delete(@RequestBody UserMallDto dto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.errorParam(UserMall.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }

            UserMall userMall = userMallRepository.findOne(dto.getId());
            if (userMall == null) {
                jsonResult.remind(UserMall.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            if (Objects.equals(userInfoDto.getId(), userMall.getUserId())) {
                jsonResult.remind("不能对自己账号进行删除操作",log);
                return;
            }
            if (userMall.getIsSuperAdmin() == Whether.YES) {
                jsonResult.remind("不能删除超级管理员",log);
                return;
            }
            // 删除用户资源
            List<AuthUserResource> authUserResourceList = authUserResourceRepository.findAuthUserResourceByMallIdAndUserId(userMall.getMallId(), userMall.getUserId());
            authUserResourceRepository.delete(authUserResourceList);
            // 删除用户
            userMallRepository.delete(userMall);

        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /v1/sso/mall_child_account_resource/update_available M端子账号 启动|停止
     * @apiGroup SSO-USER-MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {Long} id <code>必传参数</code> M端子账号id
     * @apiParam {String=YES("启用"), NO("停止")} available <code>必传参数</code> 是否启用
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功"
     * }
     */
    @RequestMapping(value = Routes.SSO_MALL_CHILD_ACCOUNT_RESOURCE_UPDATE_AVAILABLE, method = RequestMethod.PUT)
    public JsonResult updateAvailable(@RequestBody UserMallDto dto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind(UserMall.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            if (StringUtils.isBlank(dto.getAvailable()) || !EnumUtils.isValidEnum(Whether.class, dto.getAvailable())) {
                jsonResult.remind("是否启用 只允许YES(\"启用\"), NO(\"停止\")",log);
                return;
            }
            UserMall userMall = userMallRepository.findOne(dto.getId());
            if (userMall == null) {
                jsonResult.remind(UserMall.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            if (Objects.equals(userInfoDto.getId(), userMall.getUserId())) {
                jsonResult.remind("不能对自己账号进行停止或者启动操作",log);
                return;
            }
            if (userMall.getIsSuperAdmin() == Whether.YES) {
                jsonResult.remind("不能对超级管理员进行停止或者启动操作",log);
                return;
            }
            userMall.setAvailable(Whether.valueOf(dto.getAvailable()));
            userMallRepository.save(userMall);
        };
        return doing.go(request, log);
    }

}
